package org.robustcoupe.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class AsyncerTaskProcessor implements Runnable {
  private static final Log LOG = LogFactory.getLog(AsyncerTaskProcessor.class);
  private TaskAndEvent taskAndEvent;

  AsyncerTaskProcessor(Task task, TaskEvent event) {
    this(new TaskAndEvent(task, event));
  }

  AsyncerTaskProcessor(TaskAndEvent taskAndEvent) {
    checkNull(taskAndEvent);
    this.taskAndEvent = taskAndEvent;
  }

  public void run() {
    LOG.info("TaskProcessor has just started.");
    doStartedEvent(taskAndEvent);
    TaskResultType taskResult = doTask(taskAndEvent);
    doTaskCompletedEvent(taskAndEvent, taskResult);
    LOG.info("TaskProcessor has just stopped.");
  }

  void checkNull(TaskAndEvent taskAndEvent) {
    if (taskAndEvent == null) {
      throw new NullPointerException("TaskAndEvent object can`be null.");
    }
  }

  void doTaskCompletedEvent(TaskAndEvent taskAndEvent, TaskResultType taskResult) {
    if (taskAndEvent == null) {
      return;
    }
    if (taskAndEvent.isThereEvent()) {
      taskAndEvent.getEvent().taskCompleted(taskResult);
    }
  }

  TaskResultType doTask(TaskAndEvent taskAndEvent) {
    if (taskAndEvent == null) {
      return null;
    }

    TaskResultType taskResult = taskAndEvent.getTask().execute();
    return taskResult;
  }

  void doStartedEvent(TaskAndEvent taskAndEvent) {
    if (taskAndEvent == null) {
      return;
    }
    if (taskAndEvent.isThereEvent()) {
      taskAndEvent.getEvent().taskStarted();
    }
  }
}
